package com.zmx.common.common.utils.Lock;

import com.nepxion.aquarius.lock.LockExecutor;
import com.nepxion.aquarius.lock.entity.LockType;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: 基于zookeeper分布式锁
 * @ClassName: ZookeeperLock
 * @Author zhaomxr
 * @Date 2021-10-21 15:31
 */
@Component
public class ZookeeperLock {

    @Autowired
    private LockExecutor<InterProcessMutex> lockExecutor;

    private final static LockType locktype = LockType.LOCK;
    private final static String name = "Lock";
    private final static long leaseTime = 5000;
    private final static long waitTime = 0;

    public InterProcessMutex tryLock(String key) throws Exception {
        return this.tryLock(key, leaseTime, waitTime);
    }

    public InterProcessMutex tryLock(String key, long leaseTime, long waitTime) throws Exception {
        return this.tryLock(key, leaseTime, waitTime, false, false);
    }

    public InterProcessMutex tryLock(String key, long leaseTime, long waitTime, boolean async, boolean fair) throws Exception {
        return this.tryLock(LockType.LOCK, name, key, leaseTime, waitTime, async, fair);
    }

    public InterProcessMutex tryLock(LockType lockType, String name, String key, long leaseTime, long waitTime, boolean async, boolean fair) throws Exception {
        return lockExecutor.tryLock(lockType, name, key, leaseTime, waitTime, async, fair);
    }

    /**
     * 释放锁
     *
     * @param lock
     * @throws Exception
     */
    public void unlock(InterProcessMutex lock) throws Exception {
        lockExecutor.unlock(lock);
    }

    /**
     * 批量释放锁
     *
     * @param locks
     * @throws Exception
     */
    public void unlock(List<InterProcessMutex> locks) throws Exception {
        for (InterProcessMutex lock : locks) {
            this.unlock(lock);
        }
    }
}
